package com.terrace.web.tagext.easyui.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.terrace.db.system.mapper.entity.DictData;
import com.terrace.db.system.service.DictDataService;
import com.terrace.core.utils.ApplicationContextUtil;
import com.terrace.core.utils.RegularUtils;
import com.terrace.web.constant.EasyuiConstant;
import com.terrace.web.tagext.easyui.utils.EasyUIUtils;

/**
 * 表格容器
 * @author jiangyg
 *
 */
public class GridContainer implements Serializable {
	
	private static final long serialVersionUID = 5754269366796765148L;

	/**
	 * 表格name
	 */
	private String gridName;
	
	/**
	 * 是否显示选择框，默认[false]
	 */
	private boolean checkbox = false;
	
	/**
	 * 列表是否自动加载数据
	 */
	private boolean autoLoadData = true;

	/**
	 * 操作集合
	 */
	private List<GridOpt> opts = new ArrayList<GridOpt>();
	
	/**
	 * 列集合
	 */
	private List<GridColumn> columns = new ArrayList<GridColumn>();
	
	/**
	 * 表格工具集合
	 */
	private List<GridToolBar> toolbars = new ArrayList<GridToolBar>();
	
	public GridContainer() {
		super();
	}

	public GridContainer(String gridName) {
		this.gridName = gridName;
	}

	/**
	 * 新增表格列
	 * @param column
	 */
	public void addGridColumn(GridColumn column) {
		columns.add(column);
	}
	
	/**
	 * 新增表格工具
	 * @param opt
	 */
	public void addGridToolbar(GridToolBar toolbar) {
		toolbars.add(toolbar);
	}
	
	/**
	 * 新增表格操作
	 * @param opt
	 */
	public void addGridOpt(GridOpt opt) {
		opts.add(opt);
	}
	
	/**
	 * 判断是否有查询列
	 * @param columnList
	 * @return
	 */
	public boolean hasQueryColumn() {
		boolean hasQuery = false;
		for (GridColumn column : columns) {
			if(column.isQuery()){
				hasQuery =  true;
			}
		}
		return hasQuery;
	}
	
	/**
	 * 把列集合转化成js对象
	 * @param frozen
	 * @return
	 */
	public String transferColumnsToJSObject(boolean frozen) {
		StringBuffer sb = new StringBuffer();
		if (checkbox && !frozen) {
			sb.append("{field:'ck',checkbox:true},");
		}
		for (GridColumn column : columns) {
			if ((column.isFrozen() && frozen) || (!column.isFrozen() && !frozen)) {
				
				sb.append("{");
				
				// 常用属性组装
				EasyUIUtils.appendJSObjectProperty(sb, "field", column.getField());
				EasyUIUtils.appendJSObjectProperty(sb, "title", column.getTitle());
				EasyUIUtils.appendJSObjectProperty(sb, "width", column.getWidth());
				EasyUIUtils.appendJSObjectProperty(sb, "align", column.getAlign());
				EasyUIUtils.appendJSObjectProperty(sb, "hidden", column.isHidden());
				EasyUIUtils.appendJSObjectProperty(sb, "sortable", column.isSortable());

				// 显示图片
				if (column.isShowImage()) {
					JSFunction showImageFunc = new JSFunction();
					showImageFunc.addFuncParams("value", "rec", "index");
					String propertyStr = "";
					if (StringUtils.isNotBlank(column.getImageSize())) {
						String[] tld = column.getImageSize().split(",");
						propertyStr = "width=\"" + tld[0] + "\" height=\"" + tld[1] + "\"";
						tld = null;
					}
					showImageFunc.addFuncBody("return '<img " + propertyStr +" border=\"0\" src=\"'+value+'\"/>';");
					EasyUIUtils.appendJSObjectProperty(sb, "formatter", showImageFunc);
				}
				
				// 自定义链接
				if (StringUtils.isNotBlank(column.getUrl())) {
					JSFunction urlFunc = new JSFunction();
					urlFunc.addFuncParams("value", "rec", "index");
					String url = EasyUIUtils.handleOptParamOfBrace(column.getUrl(), sb, false);
					urlFunc.addFuncBody("var href=\"<a style=\'color:red\' href=\'#\' onclick=" + column.getFunname() + "('" + column.getTitle() + "','\" + " + url + " + \"')>\";return href+value+\'</a>\';");
					EasyUIUtils.appendJSObjectProperty(sb, "formatter", urlFunc);
				}
				
				// 数据字典值替换
				if (StringUtils.isNotBlank(column.getDictionary())) {
					DictDataService dictDataService = ApplicationContextUtil.getContext().getBean(DictDataService.class);
					List<DictData> dataList = dictDataService.selectDictDatasByCode(column.getDictionary());
					if (dataList != null && dataList.size() > 0) {
						sb.append("formatter:function(value,rec,index){");
						sb.append("if(value==undefined)return '';value=value+'';");
						for (int i = 0; i < dataList.size(); i++) {
							DictData dictData = dataList.get(i);
							sb.append((i > 0 ? "else" : "") + " if(value=='" + dictData.getDataValue() + "'){return '" + dictData.getDataName() + "'; }");
						}
						sb.append("else{return value;}");
						sb.append("},");
					}
				}
				
				if (StringUtils.isNotBlank(column.getFormatter())) {
					JSFunction formatterFunc = new JSFunction();
					formatterFunc.addFuncParams("value", "rec", "index");
					formatterFunc.addFuncBody("return " + column.getFormatter() + "(value,rec,index);");
					EasyUIUtils.appendJSObjectProperty(sb, "formatter", formatterFunc);
				}
				
				// 加入操作
				if (column.getField().equals("opt")) {
					sb.append("formatter:function(value,rec,index){" + this.createOptUrl() + "},");
				}
				
				EasyUIUtils.substringLastComma(sb);
				
				sb.append("},");
			}
		}
		if (sb.length() > 1 && ",".equals(sb.substring(sb.length() - 1))) {
			sb.delete(sb.length() - 1, sb.length());
		}
		return sb.toString();
	}
	
	/**
	 * 工具条转为标签
	 * @return
	 */
	public String transferToolbarToLayout() {
		StringBuffer sb = new StringBuffer();
		// 如果没有工具按钮和查询列，则不需要生成工具条
		if (toolbars.size() == 0 && !hasQueryColumn()) {
			return "";
		}
		sb.append("<div id=\"" + gridName + "ToolBar\" style=\"padding: 5px; height: auto;\">");
		
		// 查询列生成
		sb.append("<div>");
		for (GridColumn column : columns) {
			if (column.isQuery()) {
				sb.append("<span class=\"easyui-query-box\">");
				sb.append("<span class=\"easyui-query-title\" title=\"" + column.getTitle() + "\">&nbsp;" + column.getTitle() + "：</span>");
				// 查询列是字典的话，生成下拉框，否则默认生成文本框
				if (StringUtils.isNotBlank(column.getDictionary())) {
					sb.append("<input id=\"" + column.getField() + "\" name=\"" + column.getField() + "\" type=\"text\" class=\"easyui-combobox\" ");
					sb.append("data-options=\"");
					EasyUIUtils.appendDatsOption(sb, "valueField", "dataValue");
					EasyUIUtils.appendDatsOption(sb, "textField", "dataName");
					EasyUIUtils.appendDatsOption(sb, "url", EasyuiConstant.message("data.dict.code.url", column.getDictionary()));
					sb.append("\"");
					sb.append(">");
				} else {
					sb.append("<input class=\"easyui-textbox\" type=\"text\" name=\"" + column.getField() + "\" />");
				}
				sb.append("</span>");
			}
		}
		sb.append("</div>");
		
		// 操作按钮生成
		sb.append("<div style=\"height: 26px;\">");
		sb.append("<span style=\"float: left;\">");
		for (GridToolBar toolbar : toolbars) {
			sb.append("<a href=\"#\" class=\"easyui-linkbutton\" iconCls=\"" + toolbar.getIconCls() + "\" plain=\"true\" ");
			if (StringUtils.isNotBlank(toolbar.getOnclick())) {
				sb.append("onclick=\"" + toolbar.getOnclick() + "\"");
			} else if(StringUtils.isNotBlank(toolbar.getFunname())) {
				sb.append("onclick=\"" + toolbar.getFunname() + "(");
				if (StringUtils.isNotBlank(toolbar.getUrl())) {
					sb.append("'" + toolbar.getTitle() + "','" + toolbar.getUrl() + "','" + gridName + "'");
					if (StringUtils.isNotBlank(toolbar.getWidth()) || StringUtils.isNotBlank(toolbar.getHeight())) {
						String width = StringUtils.isBlank(toolbar.getWidth()) ? null
								: RegularUtils.verifyNumber(toolbar.getWidth()) ? toolbar.getWidth() : ("'" + toolbar.getWidth() + "'");
						String height = StringUtils.isBlank(toolbar.getHeight()) ? null 
								: RegularUtils.verifyNumber(toolbar.getHeight()) ? toolbar.getHeight() : ("'" + toolbar.getHeight() + "'");
						sb.append("," + width + "," + height);
					}
				}
				sb.append(")\"");
			}
			sb.append(">" + toolbar.getTitle() + "</a>");
		}
		sb.append("</span>");
		
		// 搜索和重置按钮
		sb.append("<span style=\"float: right;\">");
		if (hasQueryColumn() || (!hasQueryColumn() && !this.autoLoadData)) {
			sb.append("<a href=\"#\" class=\"easyui-linkbutton\" iconCls=\"icon-standard-magnifier\" onclick=\"" + gridName + "Search()\">查询</a>");
		}
		if (hasQueryColumn()) {
			sb.append("&nbsp;<a href=\"#\" class=\"easyui-linkbutton\" iconCls=\"icon-standard-magnifier\" onclick=\"" + gridName + "SearchReset()\">重置</a>");
		}
		sb.append("</span>");
		
		sb.append("</div>");
		
		sb.append("</div>");
		return sb.toString();
	}
	
	/**
	 * 清空表格容器
	 */
	public void clear() {
		opts.clear();
		gridName = null;
		columns.clear();
		toolbars.clear();
	}
	
	public List<GridOpt> getOpts() {
		return opts;
	}

	public List<GridColumn> getColumns() {
		return columns;
	}

	public List<GridToolBar> getToolbars() {
		return toolbars;
	}

	/**
	 * 生成操作列的URL
	 * @return
	 */
	private String createOptUrl() {
		StringBuffer sb = new StringBuffer();
		sb.append("var hrefStr='';");
		for (int p = 0; p < opts.size(); p++) {
			GridOpt opt = opts.get(p);
			String url = opt.getUrl();
			if (StringUtils.isNotBlank(url)) {
				url = EasyUIUtils.handleOptParamOfBrace(url, sb, false);
			}
			switch (opt.getOptType()) {
				case CONFIRM:
				case DELETE:
					// 提示消息处理
					String tipMessage = EasyUIUtils.handleOptParamOfBrace(opt.getMessage(), sb, false);
					sb.append("hrefStr+=\"[<a href='#' onclick=\\\"doSubmitConfirm('\"+" + url + "+\"','\"+" + tipMessage + "+\"','" + this.gridName + "')\\\">\";");
					break;
				case DIALOG:
					sb.append("hrefStr+=\"[<a href='#' onclick=\\\"dialog('" + opt.getTitle() + "','\"+" + url + "+\"'," + opt.getWidth() + "," + opt.getHeight() + ")\\\">\";");
					break;
				case FUNC:
					String funcVar = EasyUIUtils.handleOptParamOfBrace(opt.getFunname(), sb, true);
					sb.append("hrefStr+=\"[<a href='#' onclick=\\\"\"+" + funcVar + "+\"\\\">\";");
					break;
				case TAB:
					sb.append("hrefStr+=\"[<a href='#' onclick=\\\"addTab('" + opt.getTitle() + "','\"+" + url + "+\"','" + opt.getIconCls() + "')\\\">\";");
					break;
				case URL:
					sb.append("hrefStr+=\"[<a href='\"+" + url + "+\"' title='" + opt.getTitle() + "'>\";");
					break;
				default:
					break;
			}
			sb.append("hrefStr+=\"" + opt.getTitle() + "</a>]\";");
		}
		sb.append("return hrefStr;");
		return sb.toString();
	}
	
	public void setGridName(String gridName) {
		this.gridName = gridName;
	}
	
	public void setCheckbox(boolean checkbox) {
		this.checkbox = checkbox;
	}

	public void setAutoLoadData(boolean autoLoadData) {
		this.autoLoadData = autoLoadData;
	}

}
